package com.cai.servlet.user;

import com.cai.dao.UserDao;
import com.cai.dao.impl.UserDaoImpl;
import com.cai.entity.User;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;

/**
 * @author RuoLi
 * 添加用户
 */
@WebServlet(name = "ServletInsert", value = "/insert")
public class ServletInsert extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        Map<String, String[]> map = request.getParameterMap();
        User user = new User();
        user.setUser(map.get("user")[0]);
        user.setUser_name(map.get("user_name")[0]);
        user.setUser_email(map.get("user_email")[0]);
        user.setUser_type(map.get("type")[0]);
        user.setPassword(map.get("password")[0]);
        user.setUser_phone(map.get("user_phone")[0]);
        UserDao userDao = new UserDaoImpl();
        //查看用户是存在
        int count = userDao.userIsNull(map.get("user_name")[0]);
        if (count != 1) {
            //不存在 添加数据
            int num = userDao.userInsert(user);
            if (num != 0) {
                request.setAttribute("code", 1);
                //添加成功
                request.getRequestDispatcher("user_list.jsp").forward(request, response);
            } else {
                //添加失败
                request.setAttribute("code", 0);
            }
        } else {
            //存在 编辑数据
            int num = userDao.userUpdate(user);
            if (num != 0) {
                request.setAttribute("code", 1);
                //添加成功
                request.getRequestDispatcher("user_list.jsp").forward(request, response);
            } else {
                //添加失败
                request.setAttribute("code", 0);
            }
        }
    }
}
